﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using UnityEngine;
using static UnityEngine.ScreenCapture;

public class ScreenCaptureUtils 
{
    public static void Capture(bool saveFile=true,string saveName= "", Action<Texture2D> callBack=null)
    {
        Texture2D texture = DoCapture(Vector2.zero);
        SaveCapturePic(texture);
        if (callBack!=null)
        {
            callBack.Invoke(texture);   
        }

    }

    public static Texture2D Capture(Vector2 screenPos, int w = 300, int h = 300)
    {
        Texture2D texture = DoCapture(screenPos,w,h);
        return texture;

    }

    public static void SaveCapturePic(Texture2D texture,bool saveFile = true, string saveName = "")
    {
        var bytes = texture.EncodeToPNG();
        string fileName = saveName;
        if (string.IsNullOrEmpty(saveName) || !Directory.Exists(Path.GetDirectoryName(saveName)))
        {
            fileName = Path.Combine(Application.persistentDataPath, "Captures");
            if (!Directory.Exists(fileName))
            {
                Directory.CreateDirectory(fileName);
            }
            fileName = Path.Combine(fileName, "Capture.png");
        }

        File.WriteAllBytes(fileName, bytes);
    }

    public static void BuildInScreenCapture()
    {
        if (Application.isPlaying)
        {
            var fileName = Path.Combine(Application.persistentDataPath, "Captures", "Capture-RightEye.png");
            ScreenCapture.CaptureScreenshot(fileName); //全屏截图
            //ScreenCapture.CaptureScreenshot(fileName,StereoScreenCaptureMode.RightEye);
        }
    }

    private static Texture2D DoCapture(Vector2 screenPos, int w = 300, int h = 300)
    {
        Texture2D texture = new Texture2D(w, h, TextureFormat.ARGB32, false);
        //屏幕左下角为原点 screenRect
        Rect screenRect = new Rect(screenPos.x, screenPos.y, texture.width, texture.height);
        //因为需要等待unity渲染完帧才能读取像素区域 需要在协程中执行；
        //否则 unity报错ReadPixels was called to read pixels from system frame buffer, while not inside drawing frame.
        texture.ReadPixels(screenRect, 0, 0);
        texture.Apply();
        return texture;
    }
    
    

}
